import {PageContainer} from '@ant-design/pro-components';
import React, {useEffect, useState} from 'react';
import {Button, Card, Descriptions, Form, message, Input, Divider, TabsProps} from 'antd';
import {
  getInterfaceInfoByIdUsingGET,
  invokeInterfaceInfoUsingPOST,
} from '@/services/memory-api/interfaceInfoController';
import {useParams} from '@@/exports';
import {Tabs} from 'antd';
import {Space, Table, Tag} from 'antd';
import type {ColumnsType} from 'antd/es/table';
import {
  AlertFilled,
  BugFilled,
  CaretRightFilled,
  FileExclamationFilled,
  FileTextFilled,
} from "@ant-design/icons";
import Search from "antd/es/input/Search";

/**
 * 主页
 * @constructor
 */
const InterfaceInvoke: React.FC = () => {
  // 请求参数属性
  interface RequestParamsDataType {
    paramsName: string;
    isRequired: string;
    type: string;
    description: string;
  }

  // 请求参数字段
  const requestParamsColumn: ColumnsType<RequestParamsDataType> = [
    {
      title: '参数名称',
      dataIndex: 'paramsName',
      key: 'paramsName',
    },
    {
      title: '是否必选',
      dataIndex: 'isRequired',
      key: 'isRequired',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: () => (
        <>
          <Tag color={"green"}>
            String
          </Tag>
        </>
      ),
    },
    {
      title: '参数描述',
      dataIndex: 'description',
      key: 'description',
    },
  ];

  // 请求参数详细描述
  const requestParamsInfo: RequestParamsDataType[] = [
    {
      paramsName: 'category',
      isRequired: '是',
      type: 'string',
      description: '指定壁纸所属类型',
    },
  ];

  // 响应参数字段
  const responseParamsColumn = [
    {
      title: '参数名称',
      dataIndex: 'paramsName',
      key: 'paramsName',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: any) => (
        <div>
          {
            type === 'string' ? (
              <Tag color={"green"}>String</Tag>
            ) : type === 'int' ? (
              <Tag color={"blue"}>int</Tag>
            ) : 'hhh'
          }
        </div>
      ),
    },
    {
      title: '参数描述',
      dataIndex: 'description',
      key: 'description',
    },
  ];

  // 请求参数详细描述
  const responseParamsInfo = [
    {
      paramsName: 'code',
      type: 'int',
      description: '响应码',
    },
    {
      paramsName: 'data.imgList',
      type: 'string',
      description: '返回的壁纸列表',
    },
    {
      paramsName: 'data.imgList.title',
      type: 'string',
      description: '壁纸名称',
    },
    {
      paramsName: 'data.imgList.url',
      type: 'string',
      description: '壁纸链接',
    },
  ];

  const code = `
// 在这里输入你的代码
function helloWorld() {
  console.log("Hello, world!");
}
`;


  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.InterfaceInfo>();
  const [invokeRes, setInvokeRes] = useState<any>();
  const [invokeLoading, setInvokeLoading] = useState(false);

  const params = useParams();

  const loadData = async () => {
    if (!params.id) {
      message.error('参数不存在');
      return;
    }
    setLoading(true);
    try {
      const res = await getInterfaceInfoByIdUsingGET({
        id: Number(params.id),
      });
      setData(res.data);
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  // 调用接口
  const onFinish = async (values: any) => {
    if (!params.id) {
      message.error('接口不存在');
      return;
    }
    setInvokeLoading(true);
    try {
      const res = await invokeInterfaceInfoUsingPOST({
        id: params.id,
        ...values,
      });
      setInvokeRes(res.data);
      message.success('请求成功');
    } catch (error: any) {
      message.error('操作失败，' + error.message);
    }
    setInvokeLoading(false);
  };

  return (

    <PageContainer title="查看接口文档">
      <Card hoverable>
        {data ? (
          <Descriptions title={data.name} column={1}>
            <Descriptions.Item label="接口状态">{data.status ? '开启' : '关闭'}</Descriptions.Item>
            <Descriptions.Item label="描述">{data.description}</Descriptions.Item>
            <Descriptions.Item label="请求地址">{data.url}</Descriptions.Item>
            <Descriptions.Item label="请求方法">{data.method}</Descriptions.Item>
            <Descriptions.Item label="请求参数">{data.requestParams}</Descriptions.Item>
            <Descriptions.Item label="请求头">{data.requestHeader}</Descriptions.Item>
            <Descriptions.Item label="响应头">{data.responseHeader}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{data.createTime}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{data.updateTime}</Descriptions.Item>
          </Descriptions>
        ) : (
          <>接口不存在</>
        )}
      </Card>

      <Card
        title="查看开发者文档来了解如何调用该接口"
        hoverable
        style={{marginTop: 30}}
      >
        <a>接口在线文档: 随机名言</a>
      </Card>


      <Card hoverable title="在线测试" style={{marginTop: 30}}>
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              label: <><FileTextFilled/>API文档</>,
              key: '1',
              children: [
                <CaretRightFilled style={{color: "green"}}/>,
                <span style={{fontSize: 16, fontWeight: "bolder"}}>请求参数说明：</span>,
                <Table columns={requestParamsColumn} dataSource={requestParamsInfo}/>,

                <CaretRightFilled style={{color: "green"}}/>,
                <span style={{fontSize: 16, fontWeight: "bolder"}}>响应参数说明：</span>,
                <Table columns={responseParamsColumn} dataSource={responseParamsInfo}/>,

                <CaretRightFilled style={{color: "green"}}/>,
                <span style={{fontSize: 16, fontWeight: "bolder"}}>返回结果示例：</span>,
              ]
            },
            {
              label: <><BugFilled/>在线调试工具</>,
              key: '2',
              children:
                <>
                  <Search
                    placeholder="input search text"
                    allowClear
                    enterButton="Search"
                    size="large"
                  />

                  <CaretRightFilled style={{color: "green"}}/>,
                  <span style={{fontSize: 16, fontWeight: "bolder"}}>请求参数设置：</span>
                  <Table columns={requestParamsColumn} dataSource={requestParamsInfo}/>,

                  <Form name="invoke" layout="vertical" onFinish={onFinish}>
                    <Form.Item label="请求参数" name="userRequestParams">
                      <Input.TextArea/>
                    </Form.Item>
                    <Form.Item wrapperCol={{span: 16}}>
                      <Button type="primary" htmlType="submit">
                        调用
                      </Button>
                    </Form.Item>
                  </Form>
                </>
            },
            {
              label: <><FileExclamationFilled/>错误码参照</>,
              key: '3',
            },
            {
              label: <><AlertFilled/>示例代码</>,
              key: '4',
              children: 'Tab 3',
            },
          ]}
        />
      </Card>

      <Card hoverable title="返回结果" style={{marginTop: 30}} loading={invokeLoading}>
        {invokeRes}
      </Card>
    </PageContainer>
  );
};

export default InterfaceInvoke;
